package com.shibida.shibidaProject.userInfo.controller;

import com.shibida.shibidaProject.userInfo.custom.CookerDetailInfo;
import com.shibida.shibidaProject.userInfo.custom.OrderFood;
import com.shibida.shibidaProject.userInfo.dao.CookerRepository;
import com.shibida.shibidaProject.userInfo.dao.DishRepository;
import com.shibida.shibidaProject.userInfo.dao.OrderRepository;
import com.shibida.shibidaProject.userInfo.dao.UserInfoRepository;
import com.shibida.shibidaProject.userInfo.domain.CookerDetailVO;
import com.shibida.shibidaProject.userInfo.domain.DishVO;
import com.shibida.shibidaProject.userInfo.domain.OrderVO;
import com.shibida.shibidaProject.userInfo.domain.UserVO;
import org.aspectj.weaver.ast.Or;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/order")
@CrossOrigin
public class OrderController {
    @Resource
    private OrderRepository dao;
    @Resource
    private UserInfoRepository userDao;
    @Resource
    private DishRepository dishDao;
    @Resource
    private CookerRepository cookerDao;
    @Resource
    private UserBaseController userBaseController;
    @GetMapping("/allorders")
    public List<OrderVO> find(){
        List<OrderVO> list= dao.queryAll();
        for (OrderVO userItem : list) {
            String foodIdStr = userItem.getFood_id();
            userItem.setFoodsInfo(foodIdStrToCorrectFood(foodIdStr, userItem.getTar_user_id()));
            userItem.setUser_name(userDao.queryAllById(userItem.getUser_id()).getUserName());
            float totalPrice = 0f;
            for(OrderFood foodItem : userItem.getFoodsInfo()) {
                totalPrice += foodItem.getPrice() * foodItem.getNum();
            }
            userItem.setTotalPrice(totalPrice);
        }
        return list;
    }

    /**
     * 添加一个新的订单
     * @param order  从前端传过来的数据
     * @return
     */
    @PostMapping("/addOrder")
    @ResponseBody
    public int insert(@RequestBody OrderVO order){
        dao.insertOrder(order.getUser_id(),order.getTar_user_id(),order.getOrder_number(),order.getOrder_time(),order.getFood_id());
        return dao.getLastInsertedId();
    }

    @GetMapping("/orderById")
    OrderVO findOrderBtId(int id) {
        OrderVO result = dao.queryAllById(String.valueOf(id));
        CookerDetailInfo tarUserInfo = userBaseController.getCookerDetail(result.getTar_user_id());
        result.setTarUserInfo(tarUserInfo);
        String foodIdStr = result.getFood_id();
        result.setFoodsInfo(foodIdStrToCorrectFood(foodIdStr, result.getTar_user_id()));
        float totalPrice = 0f;
        for(OrderFood foodItem : result.getFoodsInfo()) {
            totalPrice += foodItem.getPrice() * foodItem.getNum();
        }
        result.setTotalPrice(totalPrice);
        result.setUser_name(userDao.queryAllById(result.getUser_id()).getUserName());
        return result;
    }
    /**
     * 将tag的id字符串转换为str字符串
     * @param idStr id字符串
     * @return 转换后的tag字符串
     */
    public List<OrderFood> foodIdStrToCorrectFood(String idStr, int cookerId) {
        if(null==idStr){
            return new ArrayList<>();
        }
        // 用户价格表
        HashMap<Integer, Float> priceTable = new HashMap<>();
        List<OrderFood> result = new ArrayList<>();
        //获取用户价格表
        List<CookerDetailVO> priceTableSrcInfo = cookerDao.queryPriceById(cookerId);
        if(priceTableSrcInfo.size() <= 0) {
            return new ArrayList<>();
        }
        CookerDetailVO item = priceTableSrcInfo.get(0);
        String[] foodIds = item.getDish().split("\\|");
        String[] foodPrices = item.getPrice().split("\\|");
        int maxIndex = Math.max(foodPrices.length, foodIds.length);
        for(int i = 0; i < maxIndex; i++) {
            priceTable.put(Integer.parseInt(foodIds[i]), Float.parseFloat(foodPrices[i]));
        }

        // 获取 菜名 菜量 单价 url
        String[] foodIdAndNum = idStr.split("\\|");
        // 1:3
        for(String foodIdAndNumItem : foodIdAndNum) {
            //1
            String[] foodSrcInfos = foodIdAndNumItem.split(":");
            if(foodSrcInfos.length == 2) {
                // 获取foodId对应的所有food信息（name， url）
                int foodId = Integer.parseInt(foodSrcInfos[0]);
                int foodNum = Integer.parseInt(foodSrcInfos[1]);
                List<DishVO> foodAll = dishDao.getAllById(foodId);
                if(foodAll.size() != 0 ) {
                    DishVO foodItem = foodAll.get(0);
                    // 添加数据
                    if(priceTable.containsKey(foodId)) {
                        result.add(new OrderFood(foodItem.getDish_name(), foodItem.getDish_url(), foodNum, priceTable.get(foodId), foodId));
                    }
                }
            }
        }
        return result;
    }
}
